package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/api/employees")
public class GetEmployeesApiServlet extends HttpServlet {
    private final CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();
    private final UserService userService = new UserServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        JsonObject result = new JsonObject();

        try {
            System.out.println("GetEmployeesApiServlet: 开始处理请求");
            
            // 获取当前用户
            HttpSession session = req.getSession();
            User user = (User) session.getAttribute("user");
            if (user == null) {
                System.out.println("GetEmployeesApiServlet: 用户未登录");
                result.addProperty("success", false);
                result.addProperty("message", "请先登录");
                out.print(gson.toJson(result));
                return;
            }
            
            System.out.println("GetEmployeesApiServlet: 当前用户ID=" + user.getId() + ", 姓名=" + user.getName() + ", 公司ID=" + user.getCompanyId());

            // 检查用户是否在公司中
            if (user.getCompanyId() == null || user.getCompanyId().isEmpty()) {
                System.out.println("GetEmployeesApiServlet: 用户不属于任何公司");
                result.addProperty("success", false);
                result.addProperty("message", "请先通过系统使用申请");
                out.print(gson.toJson(result));
                return;
            }

            // 获取公司员工列表
            String keyword = req.getParameter("keyword");
            System.out.println("GetEmployeesApiServlet: 关键词keyword=" + keyword);
            
            List<CompanyEmployee> employees;
            
            if (keyword != null && !keyword.isEmpty()) {
                System.out.println("GetEmployeesApiServlet: 搜索员工，公司ID=" + user.getCompanyId() + ", 关键词=" + keyword);
                employees = companyEmployeeService.searchCompanyEmployees(user.getCompanyId(), keyword);
            } else {
                System.out.println("GetEmployeesApiServlet: 获取所有员工，公司ID=" + user.getCompanyId());
                employees = companyEmployeeService.getCompanyEmployees(user.getCompanyId());
            }
            
            System.out.println("GetEmployeesApiServlet: 获取到员工数量：" + (employees != null ? employees.size() : "null"));

            // 过滤出已审核通过的员工
            if (employees != null) {
                int originalSize = employees.size();
                employees.removeIf(employee -> employee.getStatus() != 1);
                System.out.println("GetEmployeesApiServlet: 过滤后员工数量：" + employees.size() + "（移除了" + (originalSize - employees.size()) + "个非在职员工）");
            }

            // 创建员工数据数组
            JsonArray employeesArray = new JsonArray();
            if (employees != null) {
                for (CompanyEmployee employee : employees) {
                    JsonObject employeeObj = new JsonObject();
                    employeeObj.addProperty("userId", employee.getUserId());
                    employeeObj.addProperty("userName", employee.getUserName());
                    employeeObj.addProperty("position", employee.getPosition());
                    employeeObj.addProperty("employeeNumber", employee.getEmployeeNumber());
                    employeesArray.add(employeeObj);
                    
                    System.out.println("GetEmployeesApiServlet: 添加员工 - userId=" + employee.getUserId() + 
                            ", userName=" + employee.getUserName() + 
                            ", position=" + employee.getPosition() + 
                            ", employeeNumber=" + employee.getEmployeeNumber());
                }
            }

            result.addProperty("success", true);
            result.add("employees", employeesArray);
        } catch (Exception e) {
            System.out.println("GetEmployeesApiServlet: 发生错误：" + e.getMessage());
            e.printStackTrace();
            result.addProperty("success", false);
            result.addProperty("message", "系统错误: " + e.getMessage());
        }

        out.print(gson.toJson(result));
        System.out.println("GetEmployeesApiServlet: 请求处理完成");
    }
} 